package com.sina.finance.api.framework.service.impl;

import com.sina.finance.api.framework.constants.Constants;
import com.sina.finance.api.framework.constants.ErrorCodeConstants;
import com.sina.finance.api.framework.response.Response;
import com.sina.finance.api.framework.service.BizIdAndAppKeyService;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 如果系统的业务标识不是使用AppKey, 那么除了使用AppKey见证是否可以使用接口外, 还需要验证业务标识与key对应的是同一个人.
 */
public class BusinessIdKeyDiffSecurityServiceImpl extends SecurityServiceImpl {

	public static final String PARTNER_CODE = "account_id";

	@Resource
	private BizIdAndAppKeyService bizIdAndAppKeyService;

	@Override
	public Response verifyRequest(Map<String, String[]> requestParams) {

		if(!this.hasParam(requestParams, PARTNER_CODE)){
			return errorResponseService.getErrorResponse(ErrorCodeConstants.SYS_ERROR_CODE_S15);
		}

		String partnerCode = requestParams.get(PARTNER_CODE)[0];

		// 如果没有传递app_key
		if(!this.hasParam(requestParams, Constants.SYS_PARAM_APP_KEY)){
			return errorResponseService.getErrorResponse(ErrorCodeConstants.SYS_ERROR_CODE_S2);
		}

		String appKey = requestParams.get(Constants.SYS_PARAM_APP_KEY)[0];

		if (!bizIdAndAppKeyService.isBizIdAndKeyBelongSamePerson(partnerCode, appKey)) {
			return errorResponseService.getErrorResponse(ErrorCodeConstants.SYS_ERROR_CODE_S14);
		}

		return super.verifyRequest(requestParams);
	}

}
